package com.kaifamiao.demo.d0826;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Date;

public class Demo {

    /**
     * 计算下一个生日还有多久
     * @param date 生日字符串. 格式：MM-dd eg： 10-01
     * @return
     */
    public static long getNextBirthdayDays(String date){
        // 判断字符串是否为 null
        if (date == null){
            throw new NullPointerException("需要传递一个生日");
        }
        LocalDate now = LocalDate.now(); // 2022-08-26
        // 今年生日的日期字符串
        String birthday = now.getYear() + "-" + date;
        // 转换为 LocalDate
        LocalDate next = LocalDate.parse(birthday);

        // 方案一 toEpochDay() 日期转换为纪元日， 从 1970-01-01 到指定日期的天数
        long nowDays = now.toEpochDay();
        long birthdayDays = next.toEpochDay();

        if (now.isAfter(next)){
            // 今年生日已经过了, 后一年
//            next = next.plus(1, ChronoUnit.YEARS);
            next = next.plusYears(1);
            birthdayDays = next.toEpochDay();
        }

        return birthdayDays - nowDays;
    }

    public static long getNextBirthdayDays2(String date){
        // 判断字符串是否为 null
        if (date == null){
            throw new NullPointerException("需要传递一个生日");
        }
        LocalDate now = LocalDate.now(); // 2022-08-26
        // 今年生日的日期字符串
        String birthday = now.getYear() + "-" + date;
        // 转换为 LocalDate
        LocalDate next = LocalDate.parse(birthday);

        // 方案二 until() 计算两个 日期间的差值
        if (now.isAfter(next)){
            // 今年生日过了
            next = next.plusYears(1);
        }
        return now.until(next, ChronoUnit.DAYS);
    }


    public static long getAnniversaryDaysAfter(String date){
        // 判断字符串是否为 null
        if (date == null){
            throw new NullPointerException("需要传递一个生日");
        }
        LocalDate now = LocalDate.now();
        LocalDate anniversary = LocalDate.parse(date);
        return anniversary.until(now, ChronoUnit.DAYS);
    }

    public static long get(String date, String otherDate){
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date d = dateFormat.parse(date);
            Date d1 = dateFormat.parse(otherDate);

            long time = d.getTime() - d1.getTime();

            double floor = Math.floor(time / 1000.0 / 60 / 60 / 24);

            return Math.round(floor);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return -1;
    }

    public static void main(String[] args) {
//        String birthday = "05-01";
//        System.out.println(getNextBirthdayDays2(birthday));

//        String anniversary = "2022-07-13";
//        System.out.println(getAnniversaryDaysAfter(anniversary));

        String d = "2022-08-26";
        String d1 = "2022-08-22";

        System.out.println(get(d, d1));

    }
}
